﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.OleDb;
using System.Windows.Forms;

namespace Login
{
    class DbOp
    {
        OleDbConnection dbConn = new OleDbConnection();
        OleDbCommand dbCmd = new OleDbCommand();
        OleDbDataAdapter dbAdapter = new OleDbDataAdapter();

        public DbOp(string strConn)
        {
            dbConn.ConnectionString = strConn;
            dbCmd.Connection = dbConn;
            dbAdapter.SelectCommand = dbCmd;
        }

        public void AddParams(params object[] vals)
        {
            dbCmd.Parameters.Clear();
            if (vals != null)
            {
                foreach (object val in vals)
                {
                    OleDbParameter param = new OleDbParameter();
                    param.Value = val;
                    dbCmd.Parameters.Add(param);
                }
            }
        }

        public DataTable GetDataTable(string sql, params object[] vals)
        {
            DataTable dt = new DataTable();
            dbCmd.CommandText = sql;
            AddParams(vals);
            dbAdapter.Fill(dt);
            return dt;
        }

        public int ExecuteNonQuery(string sql, params object[] vals)
        {
            int rowAffected = -1;
            try
            {
                if (dbConn.State != ConnectionState.Open)
                {
                    dbConn.Open();
                }
                dbCmd.CommandText = sql;
                AddParams(vals);
                rowAffected = dbCmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                if (dbConn.State == ConnectionState.Open)
                {
                    dbConn.Close();
                }
            }
            return rowAffected;
        }
    }
}
